from database import db
from ..models.order import OrderDetail, OrderDetailAdditional, Order


class OrderService(object):
    @classmethod
    def create_order(cls, *args, **kwargs):
        kwargs.setdefault('status', Order.STATUS_CREATED)
        order = Order(**kwargs)
        # db.session.add(order)
        return order

    @classmethod
    def get_order_by_id(cls, id):
        return Order.query.filter(Order.id == id).first()
    @classmethod
    def save_order(cls, order):
        if not order.real_amount:
            order.real_amount = order.amount
        if not order.fee:
            order.fee = 0.00
        if not order.real_fee:
            order.real_fee = order.fee
        import datetime
        order.updated_at = datetime.datetime.now()
        db.session.add(order)
        db.session.commit()

    @classmethod
    def create_order_detail_by_item(cls, cart_item, currency):
        amount = currency.transform_amount(cart_item.offer.price) * cart_item.count
        order_detail = OrderDetail(
            count=cart_item.count,
            # description='{} * {}'.format(cart_item.product.title, cart_item.count)
        )
        order_detail.product = cart_item.product

        additives = cart_item.additives or []

        for additional in additives:
            additional_amount = additional.calc_amount(currency, cart_item.offer.price) * cart_item.count
            amount += additional_amount
            order_detail_additional = OrderDetailAdditional(
                count=cart_item.count,
                amount=additional_amount
            )
            order_detail_additional.additional = additional
            order_detail.additionals.append(order_detail_additional)
        order_detail.amount = amount
        order_detail.real_amount = amount
        # order_detail.dealer_id = cart_item.offer.dealer_id
        order_detail.product = cart_item.product
        return order_detail
